package cn.gavin.service.impl;

import cn.gavin.domain.Employee;
import cn.gavin.exception.LogicException;
import cn.gavin.mapper.EmployeeMapper;
import cn.gavin.qo.QueryObject;
import cn.gavin.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void deleteById(Long id) {
        employeeMapper.deleteRelation(id); // 删除关系
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void insert(Employee employee, Long[] ids) {
        employeeMapper.insert(employee);
        // 处理中间表
        if (ids != null && ids.length > 0){ // 数组不为空时才添加
            employeeMapper.insertRelation(employee.getId(),ids);
        }
    }

    @Override
    public Employee findById(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        // 删除关系
        employeeMapper.deleteRelation(employee.getId());
        // 关联关系
        if (ids != null && ids.length > 0){
            employeeMapper.insertRelation(employee.getId(),ids);
        }
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee> employees = employeeMapper.dataList(qo);
        return new PageInfo<>(employees);
    }

    @Override
    public Employee login(String username, String password) {
        // 判断登录信息不能为空
        if (!StringUtils.hasText(username)){
            throw new LogicException("用户名不能为空");
        }
        if (!StringUtils.hasText(password)){
            throw new LogicException("密码不能为空");
        }
        // 检测用户是否登录正确
        Employee employee = employeeMapper.selectByUsernameAndPassword(username,password);
        if (employee == null){
            throw new LogicException("帐号或密码错误");
        }
        return employee;
    }

    @Override
    public Employee selectByUsername(String username) {
        return employeeMapper.selectByUsername(username);
    }

    @Override
    public Workbook exportXls() {
        // 查询所有员工信息
        List<Employee> employees = employeeMapper.selectAll();
        // 生成一个 excel，并且返回给浏览器（文件下载）
        Workbook wb = new HSSFWorkbook();
        // 创建表格
        Sheet sheet = wb.createSheet("员工通讯录");
        // 创建标题行
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("用户名");
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("邮箱");
        row.createCell(3).setCellValue("年龄");
        for (int i = 0; i < employees.size(); i++) {
            // 获取员工对象
            Employee employee = employees.get(i);
            // 创建行
            row = sheet.createRow(i + 1);
            // 创建单元格（列号）
            row.createCell(0).setCellValue(employee.getUsername());
            row.createCell(1).setCellValue(employee.getName());
            row.createCell(2).setCellValue(employee.getEmail());
            row.createCell(3).setCellValue(employee.getAge());
        }
        return wb;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        // 把文件输入流传给 POI 读取
        Workbook workbook = new HSSFWorkbook(file.getInputStream());
        // 读取第一张表格
        Sheet sheet = workbook.getSheetAt(0);
        // 获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        // 标题行不读
        for (int i = 1; i <= lastRowNum; i++) {
            Employee employee = new Employee();
            // 一行行读
            Row row = sheet.getRow(i);
            // 读单元格
            employee.setUsername(row.getCell(0).getStringCellValue());
            employee.setName(row.getCell(1).getStringCellValue());
            employee.setEmail(row.getCell(2).getStringCellValue());
            employee.setAge((int)row.getCell(3).getNumericCellValue()); // 数字格式用这个获取，获取出来是 double 类型，所以要强转
            // 插入到数据库
            employeeMapper.insert(employee);
        }
    }
}
